import { reqLogin, reqGetUserinfo, reqGetUserDatailById } from '@/api/user'
import { getToken, setToken } from '@/utils/auth.js'

const state = () => {
  return {
    token: getToken() || null,
    UserInfo: {}
  }
}

const mutations = {
  setToken(state, newToken) {
    // 存入vuex中
    state.token = newToken
    // 持久化
    setToken(newToken)
  },
  // 清空token
  removeToken(state) {
    state.token = null
  },
  // 设置用户信息
  setUserInfo(state, UserInfo) {
    state.UserInfo = UserInfo
  },
  // 清除用户信息
  removeUserInfo(state) {
    state.UserInfo = {}
  }
}
const actions = {
  async login(context, data) {
    const res = await reqLogin(data)
    context.commit('setToken', res.data)
    // return res
  },
  // 获取用户资料
  async getUserInfo(context) {
    const { data: res1 } = await reqGetUserinfo()
    const { data: res2 } = await reqGetUserDatailById(res1.userId)
    const res = { ...res1, ...res2 }
    context.commit('setUserInfo', res)
    // console.log(res)
  },
  // 退出
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

